package leetcode;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * Created by baoyunfeng on 2019/8/18.
 */
public class DFS_BFS {

    public void main(String args[]) {

    }

    public void DFSWithRecursion(TreeNode root) {
        if (root == null) {
            return;
        }
        doSomething(root);
        if (root.left != null) {
            DFSWithRecursion(root.left);
        }
        if (root.right != null) {
            DFSWithRecursion(root.right);
        }
    }

    public void DFSWithStack(TreeNode root) {
        if (root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);

        while (!stack.isEmpty()) {
            TreeNode treeNode = stack.pop();
            doSomething(treeNode);
            if (treeNode.right != null) {
                stack.push(treeNode.right);
            }
            if (treeNode.left != null) {
                stack.push(treeNode.left);
            }
        }
    }

    public void BFSWithQueue(TreeNode root) {
        if (root == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            TreeNode treeNode = queue.poll();
            doSomething(treeNode);
            if (treeNode.left != null) {
                queue.add(treeNode.left);
            }
            if (treeNode.right != null) {
                queue.add(treeNode.right);
            }
        }
    }

    private void doSomething(TreeNode node) {

    }

    class TreeNode {

        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }
}
